def bound_range_str(r):
    a=r[0]
    b=r[-1]
    if a in "[]": r=r[1:]
    if b in "[]":r=r[:-1]
    
    t=[i.strip() for i in r.split(':')]
    pn=0
    tmp=[len(i.split('.')[1]) for i in t if '.' in i]
    if tmp:
        pn=max(tmp)
    pf=10**-pn
    pi=10**pn
    if len(t)==1:
        return t
    t=[int(float(i)*pi) for i in t]
    if len(t)==2:
        t.append(1)
        t[-1]*=pi
    if a=="]":t[0]+=t[-1]
    if b=="]":t[1]+=t[-1]
    if pn==0:
        return [str(int(round(i*pf))) for i in range(*t)]
    else:
        return [str(round(i*pf,pn)) for i in range(*t)]

def __permute_inc(l,p):
    n=len(p)-1
    while n>=0:
        p[n]+=1
        if p[n]==l[n]:
            p[n]=0
            n-=1
        else:
            return 0
    return 1
def permute(k,d,n):
    l=[]
    l2=[]
    r={}
    for i in k:
        if type(d[i])==list:
            l.append(len(d[i]))
            l2.append(i)
#            l.insert(0,len(d[i]))
#            l2.insert(0,i)
        else:
            r[i]=d[i]
    ln=len(l)
    p=[0]*ln
    for i in range(n):
        n+=1
        __permute_inc(l,p)
    m=0
    for i in l2:
        r[i]=d[i][p[m]]
#        print i,"m=",m,"p[m]=",p[m],d[i][p[m]]
        m+=1
    yield (n,r)
    while __permute_inc(l,p)==0:
        m=0
        n+=1
        for i in l2:
            r[i]=d[i][p[m]]
            m+=1
        yield (n,r)

def cal_nit(d):
#   calculates number of iterations
    s=1
    for i in d:
        if type(d[i])==list:s*=len(d[i])
    return s

def parse_par_file(filename):
    lt=open(filename).readlines()
    l=[]
    d={}
    for i in lt:
        t=i.split(':=')
        if len(t)==2:
            t[0]=t[0].strip()
            t[1]=t[1].strip()
            l.append(t[0])
            d[t[0]]=bound_range_str(t[1])
            continue
        t=i.split('=')
        if len(t)==2:
            t[0]=t[0].strip()
            t[1]=t[1].strip()
            l.append(t[0])
            d[t[0]]=t[1]
    return l,d

def build(templ_file,file,d):
    s=open(templ_file,'r').read()
    for i in d:
        s=s.replace("@T$%s$T@" % i,d[i])
    open(file,'w').write(s)

def iterate_build(tmplfile,parfile):
    l,d=parse_par_file(parfile)
    n=cal_nit(d)
    mn,ex=d["LOGFILENAME"].split('.')
    st="_%%0%dd" % len(str(n))
    for n,r in permute(l,d,0):
        cfile=mn+st%n+".c"
        r["LOGFILENAME"]=mn+st%n+"."+ex
        build(tmplfile,cfile,r)
    

#build('ga_bc_01_4test.tmpl','1.c',d)